﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace HRX.PayCenter.Common
{
    /// <summary>
    /// json.net辅助类
    /// </summary>
    public static class NewtonsoftJsonHelper
    {
        /// <summary>
        /// 反序化成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(this string jsonStr)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonStr);
            }
            catch (JsonException ex)
            {
                ex.Data["jsonStr"] = jsonStr;
                throw;
            }
        }

        public static object DeserializeObject(this string jsonStr)
        {
            try
            {
                return JsonConvert.DeserializeObject(jsonStr);
            }
            catch (JsonException ex)
            {
                ex.Data["jsonStr"] = jsonStr;
                throw;
            }
        }

        public static object DeserializeObject(this string jsonStr, Type type)
        {
            try
            {
                return JsonConvert.DeserializeObject(jsonStr, type);
            }
            catch (JsonException ex)
            {
                ex.Data["jsonStr"] = jsonStr;
                throw;
            }
        }

        /// <summary>
        /// 序列化成字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonObj"></param>
        /// <returns></returns>
        public static string SerializeObject<T>(this T jsonObj)
        {
            return JsonConvert.SerializeObject(jsonObj);
        }
    }
}
